//
//  HmHttpRequest.m
//  SmartHomeSDK
//
//  Created by haimen_ios_imac on 2017/7/4.
//  Copyright © 2017年 深圳海曼科技有限公司. All rights reserved.
//

#import "HmHttpRequest.h"

@implementation HmHttpRequest

- (AFHTTPSessionManager *)getManager
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript", @"text/xml", nil];
    return manager;
}

#pragma mark 封装请求方法
/*
{
    FBillNo = "<null>";
    FInterID = 0;
    FIsFooterData = 0;
    FIsNeedRelogin = 0;
    FIsSuccess = 1;
    FMsg = "\U767b\U5f55\U6210\U529f!";
    FObject =     {
        FAccessToken = "73f9ce5c-5dc5-4eea-855f-53755040b530";
        FExpireIn = "2017-07-14T11:30:27.133";
        FPhone = 13430510995;
        FRefreshToken = "83eb1296-d645-4b02-8699-6c5a3ee73db4";
    };
    rows =     (
    );
}
 */
- (void)afnRequest:(NSString *)url
     requestMethod:(NSString *)method
            header:(NSMutableDictionary *)headDict
            params:(NSMutableDictionary *)params
{
    AFHTTPSessionManager *manager = [self getManager];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", url_domin, url];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:urlString parameters:params error:nil];
    
    for (NSString *key in headDict) {
        [request addValue:[headDict objectForKey:key] forHTTPHeaderField:key];
    }
    
    NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (error) {
            if (self.tcResponseBlock)
                self.tcResponseBlock(NO, nil, nil, nil);
            
        } else {
            id responseValue = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            BOOL isSuccess = NO;
            if ([responseValue isKindOfClass:[NSDictionary class]]) {
                NSInteger success = [[responseValue objectForKey:@"FIsSuccess"] integerValue];
                if (success == 1)
                    isSuccess = YES;
                NSString *msg = [responseValue objectForKey:@"FMsg"];
                id obj = [responseValue objectForKey:@"FObject"];
                if (self.tcResponseBlock)
                    self.tcResponseBlock(isSuccess, msg, obj, responseValue);
            } else {
                if (self.tcResponseBlock)
                    self.tcResponseBlock(isSuccess, nil, nil, nil);
            }
        }
        
    }];
    [task resume];
}

- (void)uploadData:(NSData *)data
            header:(NSDictionary *)header
               url:(NSString *)url
{
    AFHTTPSessionManager *manager = [self getManager];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer]
                                    requestWithMethod:@"POST"
                                    URLString:url
                                    parameters:nil
                                    error:nil];
    for (NSString *key in header) {
        [request addValue:[header objectForKey:key] forHTTPHeaderField:key];
    }
    
    NSURLSessionUploadTask * uploadtask = [manager uploadTaskWithRequest:request fromData:data progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"uploadProgress : %@", uploadProgress);
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"dict : %@", dict);
        
    }];
    
    [uploadtask resume];
}

#pragma mark- 上传图片方法
- (NSURLSessionUploadTask*)uploadTaskWithImage:(UIImage*)image
                                           url:(NSString *)url
                                    completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
    // 构造 NSURLRequest
    AFHTTPSessionManager *manager = [self getManager];
    NSError* error = NULL;
    NSString *urlString = [NSString stringWithFormat:@"%@%@", url_domin, url];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
    {
        NSData* imageData = UIImageJPEGRepresentation(image, 0.1);
         [formData appendPartWithFileData:imageData
                                     name:@"xxxxx"
                                 fileName:@"test.jpg"
                                 mimeType:@"image/jpg"];
    } error:&error];
    
    NSMutableDictionary *header = [self getAccessKey];
    [header addEntriesFromDictionary:[self getAccessTokenDict]]; 
    for (NSString *key in header) {
        [request addValue:[header objectForKey:key] forHTTPHeaderField:key];
    }
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
    } completionHandler:completionBlock];
    return uploadTask;
}

- (void)uploadMutilImage:(NSArray *)images
                     url:(NSString *)url 
{
    // 准备保存结果的数组，元素个数与上传的图片个数相同，先用 NSNull 占位
    NSMutableArray* result = [NSMutableArray array];
    dispatch_group_t group = dispatch_group_create();
    for (NSInteger i = 0; i < images.count; i++) {
        
        dispatch_group_enter(group);
        NSURLSessionUploadTask* uploadTask = [self uploadTaskWithImage:images[i]
                                                                   url:url
                                                            completion:^(NSURLResponse *response, id responseObject, NSError *error) {
            
            id responseValue = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            BOOL isSuccess = NO;
            if ([responseValue isKindOfClass:[NSDictionary class]]) {
                NSInteger success = [[responseValue objectForKey:@"FIsSuccess"] integerValue];
                if (success == 1)
                    isSuccess = YES;
                //NSString *msg = [responseValue objectForKey:@"FMsg"];
                id obj = [responseValue objectForKey:@"FObject"];
                
                if (!isSuccess) {
                    
                    NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, error);
                    dispatch_group_leave(group);
                } else {
                    NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, responseObject);
                    @synchronized (result) { // NSMutableArray 是线程不安全的，所以加个同步锁
                        [result addObject:obj[@"fullUrl"]];
                        //[NSString stringWithFormat:@"%@%@", url_domin, obj[@"fullUrl"]]];
//                        result[i] = [NSString stringWithFormat:@"%@%@", url_domin, obj];
                    }
                    dispatch_group_leave(group);
                }
            }
        }];
        [uploadTask resume];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        NSLog(@"上传完成!");
        if (self.tcUploadImageBlock) {
            self.tcUploadImageBlock(result);
        }
    });
}


@end
